package com.geega.geetest.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.geega.geetest.constant.Constants;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

@Slf4j
public class TokenUtil {
    private static final long EXPIRE_TIME = 12 * 60 * 60 * 1000;//token到期时间10小时
    private static final String TOKEN_SECRET = "ljdyaishijin**3nkjnj??";  //密钥盐


    public static String sign(String account,String userId) {
        String token = null;
        try {
            Date expireAt = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            token = JWT.create()
                    .withIssuer(Constants.issure)//发行人
                    .withClaim(Constants.account, account)//存放数据
                    .withClaim(Constants.userId, userId)//存放数据
                    .withExpiresAt(expireAt)//过期时间
                    .sign(Algorithm.HMAC256(TOKEN_SECRET));
        } catch (IllegalArgumentException | JWTCreationException je) {
            log.error(je.getMessage(), je);
        }
        return token;
    }

    public static Boolean verify(String token) {
        if (StrUtil.isNotBlank(token)) {
            try {
                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer(Constants.issure).build();//创建token验证器
                DecodedJWT decodedJWT = jwtVerifier.verify(token);
                log.info("account: {}", decodedJWT.getClaim(Constants.account).asString());
                log.info("userId: {}", decodedJWT.getClaim(Constants.userId).asString());
                log.info("过期时间： {}", DateUtil.formatDateTime(decodedJWT.getExpiresAt()));
                return true;
            } catch (IllegalArgumentException | JWTVerificationException e) {
                return false;
            }
        }
        return false;
    }

    public static String getAccount(String token, String claim) {
        String account = null;
        try {
            DecodedJWT jwt = JWT.decode(token);
            account = jwt.getClaim(claim).asString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return account;
    }

    public static Long getUserId(String token, String claim) {
        Long userId = null;
        try {
            DecodedJWT jwt = JWT.decode(token);
            userId = Long.parseLong(jwt.getClaim(claim).asString());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return userId;
    }
}
